package de.gzork.zmpp;

import java.io.InputStream;

import org.zmpp.ExecutionControl;
import org.zmpp.base.DefaultMemory;
import org.zmpp.encoding.DefaultAccentTable;
import org.zmpp.encoding.ZsciiEncoding;
import org.zmpp.vm.MachineRunState;
import org.zmpp.vm.MachineFactory.MachineInitStruct;
import org.zmpp.windowing.AnnotatedText;
import org.zmpp.windowing.BufferedScreenModel;

public class ZmppWrapperFactory {
	public static ZmppWrapper createMiniZork(String username) {
		String storyFileName = "/minizork.z3";
		InputStream storyFileStream = ZmppWrapperFactory.class.getResourceAsStream(storyFileName);
		
		ZmppWrapper zmpp = null;
		try {
			MachineInitStruct initStruct = new MachineInitStruct();
			if (storyFileName.endsWith("zblorb")) {
				initStruct.blorbFile = storyFileStream;
			} else {
				initStruct.storyFile = storyFileStream;
			}

			InputStream storyFileStream2 = ZmppWrapperFactory.class.getResourceAsStream(storyFileName);
			BufferedScreenModel screenModel = new BufferedScreenModel();
			byte[] data = new byte[storyFileStream.available()];
			storyFileStream2.read(data);
			storyFileStream2.close();

			screenModel.init(new DefaultMemory(data), new ZsciiEncoding(new DefaultAccentTable()));

			initStruct.saveGameDataStore = new DBSaveGameDataStore(username);
//			initStruct.saveGameDataStore = new MemorySaveGameDataStore();
			initStruct.screenModel = screenModel;
			initStruct.ioSystem = new IOSystemTextBased();
			initStruct.ioSystem.getTranscriptWriter();

			ExecutionControl executionControl = new ExecutionControl(initStruct);
//			executionControl.getMachine().save(executionControl.getMachine().getPC()+1);
			
			MachineRunState runState = executionControl.run();

			for (AnnotatedText text : screenModel.getLowerBuffer()) {
				System.out.println(text.getText().replaceAll(">", ""));
			}
			
			zmpp = new ZmppWrapper(screenModel, executionControl);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (storyFileStream != null) {
				try {
					storyFileStream.close();
				} catch (Exception ioex) {
				}
			}
		}

		return zmpp;
	}
}
